package com.example.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @Author: springBoot
 * @Description: 用于统计接口调用时长
 * @Date: 2025/8/18 上午9:35
 * @Version: 1.0
 */
@Slf4j
public class TimeInterceptor implements HandlerInterceptor {

    LocalDateTime beginTime;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 开始时间
        beginTime = LocalDateTime.now();

        // 日志
        log.info("当前请求:{};开始时间:{}", request.getRequestURI(), beginTime);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        // 结束时间
        LocalDateTime endTime = LocalDateTime.now();

        // 日志
        log.info("当前请求:{};结束时间:{}", request.getRequestURI(), endTime);

        // 计算2个时间差
        Duration between = Duration.between(beginTime, endTime);

        // 获取时间差 -- 毫秒
        long millis = between.toMillis();
        long nanos = between.toNanos();

        if (millis > 0) {
            log.info("当前请求:{};执行时间:{}毫秒", request.getRequestURI(), millis);
        } else {
            log.info("当前请求:{};执行时间:{}纳秒", request.getRequestURI(), nanos);
        }

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
